package com.dxx.cloud.admin.controller.toc;

import com.alibaba.nacos.common.utils.RandomUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.dxx.cloud.admin.enums.CacheKeyEnums;
import com.dxx.cloud.admin.module.entity.CustomerEntity;
import com.dxx.cloud.admin.module.request.CustomerLoginRequest;
import com.dxx.cloud.admin.service.ICustomerService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.dromara.common.core.domain.R;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 37048
 */
@RestController
@RequestMapping("/toc/customer")
public class CustomerController {

    @Resource
    private ICustomerService customerService;

    @PostMapping("/login")
    @Operation(summary = "登录", description = "登录")
    public R<CustomerEntity> login(@RequestBody CustomerLoginRequest request) {
        final CustomerEntity customer = customerService.loginByCode(request.getMobile(), request.getAuthCode());
        if(null != customer) {
            return R.ok(customer);
        }
        return R.fail("用户名或密码错误");
    }

    @PostMapping("/sendAuthCode")
    @Operation(summary = "发送短信验证码", description = "发送短信验证码")
    public R<CustomerEntity> sendAuthCode(@RequestBody CustomerLoginRequest request) {
        final String cacheObject = RedisUtils.getCacheObject(CacheKeyEnums.LOGIN.toKey(request.getMobile()));
        if (StringUtils.hasText(cacheObject)) {
           return R.fail("请勿重复发送验证码");
        }
        RedisUtils.setCacheObject(CacheKeyEnums.LOGIN.toKey(request.getMobile()), String.valueOf(RandomUtils.nextInt(100000, 999999)),
                CacheKeyEnums.LOGIN.getDuration());
        return R.ok("发送成功");
    }

    @PostMapping("/updateById")
    @Operation(summary = "更新用户信息", description = "更新用户信息")
    public R<Boolean> updateById(@RequestBody CustomerEntity request) {
        Assert.notNull(request.getId(),"用户id不能为空");
        return R.ok(customerService.updateById(request));
    }
}
